<template>
  <div class="create-order-page">
    <div class="header">
      <div class="header-content">
        <div class="back-btn" @click="$router.push('/')">←</div>
        <div class="header-title">创建代取订单</div>
        <div class="placeholder"></div>
      </div>
    </div>

    <div class="main-content">
      <div class="form-container">
        <div class="form-group">
          <label class="form-label" for="express-company">快递公司</label>
          <div class="select-wrapper">
            <select class="form-select" id="express-company" v-model="form.expressCompany">
              <option value="" disabled>请选择快递公司</option>
              <option value="顺丰">顺丰</option>
              <option value="中通">中通</option>
              <option value="圆通">圆通</option>
              <option value="申通">申通</option>
              <option value="韵达">韵达</option>
              <option value="京东">京东</option>
              <option value="邮政">邮政</option>
              <option value="其他">其他</option>
            </select>
          </div>
        </div>

        <div class="form-group">
          <label class="form-label" for="express-type">快递类型</label>
          <div class="select-wrapper">
            <select class="form-select" id="express-type" v-model="form.expressType">
              <option value="" disabled>请选择快递类型</option>
              <option value="文件">文件</option>
              <option value="小件">小件</option>
              <option value="中件">中件</option>
              <option value="大件">大件</option>
            </select>
          </div>
        </div>

        <div class="form-group">
          <label class="form-label required" for="package-count">包裹数量</label>
          <input type="number" class="form-input" id="package-count" v-model="form.packageCount" placeholder="请输入包裹数量" min="1">
          <div class="error-message" v-if="errors.packageCount">请填写包裹数量</div>
        </div>

        <div class="form-group">
          <label class="form-label required" for="package-size">包裹大小</label>
          <div class="select-wrapper">
            <select class="form-select" id="package-size" v-model="form.packageSize" :class="{ error: errors.packageSize }">
              <option value="" disabled>请选择包裹大小</option>
              <option value="小件">小件 (≤1kg)</option>
              <option value="中件">中件 (1-3kg)</option>
              <option value="大件">大件 (3-5kg)</option>
              <option value="超大件">超大件 (>5kg)</option>
            </select>
          </div>
          <div class="error-message" v-if="errors.packageSize">请选择包裹大小</div>
        </div>

        <div class="form-group">
          <label class="form-label required" for="estimated-weight">预估重量 (kg)</label>
          <input type="text" class="form-input" id="estimated-weight" v-model="form.estimatedWeight" placeholder="例如：1.5、2.0" :class="{ error: errors.estimatedWeight }">
          <div class="weight-example">请填写预估重量，如1.5、2.0等</div>
          <div class="error-message" v-if="errors.estimatedWeight">请填写预估重量</div>
        </div>

        <div class="form-group">
          <label class="form-label required" for="pickup-code">取件码</label>
          <input type="text" class="form-input" id="pickup-code" v-model="form.pickupCode" placeholder="请输入取件码，多个取件码请用逗号分隔" :class="{ error: errors.pickupCode }">
          <div class="code-example">多个取件码请用逗号分隔，例如：A1-123,B2-456</div>
          <div class="error-message" v-if="errors.pickupCode">请填写取件码</div>
        </div>

        <div class="form-group">
          <label class="form-label required" for="pickup-address">取件地址</label>
          <input type="text" class="form-input" id="pickup-address" v-model="form.pickupAddress" placeholder="例如：菜鸟驿站、近邻宝等" :class="{ error: errors.pickupAddress }">
          <div class="error-message" v-if="errors.pickupAddress">请填写取件地址</div>
        </div>

        <div class="form-group">
          <label class="form-label required" for="delivery-address">送达地址</label>
          <input type="text" class="form-input" id="delivery-address" v-model="form.deliveryAddress" placeholder="例如：宿舍楼号房间号" :class="{ error: errors.deliveryAddress }">
          <div class="error-message" v-if="errors.deliveryAddress">请填写送达地址</div>
        </div>

        <div class="form-group">
          <label class="form-label required">期望送达时间</label>
          <div class="delivery-time-group">
            <div class="time-options">
              <div class="time-option" :class="{ selected: form.deliveryTimeType === '1' }" @click="selectDeliveryTime('1')">1小时内</div>
              <div class="time-option" :class="{ selected: form.deliveryTimeType === '2' }" @click="selectDeliveryTime('2')">2小时内</div>
              <div class="time-option" :class="{ selected: form.deliveryTimeType === '4' }" @click="selectDeliveryTime('4')">4小时内</div>
              <div class="time-option" :class="{ selected: form.deliveryTimeType === 'custom' }" @click="selectDeliveryTime('custom')">自定义时间</div>
            </div>

            <div class="datetime-inputs" v-if="form.deliveryTimeType === 'custom'">
              <div class="date-input">
                <input type="date" class="form-input" v-model="form.deliveryDate" :min="minDate">
              </div>
              <div class="time-input">
                <input type="time" class="form-input" v-model="form.deliveryTime">
              </div>
            </div>
          </div>
          <div class="error-message" v-if="errors.deliveryTime">请选择期望送达时间</div>
        </div>

        <div class="form-group">
          <label class="form-label required" for="custom-price">自定义价格 (元)</label>
          <input type="number" class="form-input" id="custom-price" v-model="form.customPrice" placeholder="请输入代取服务价格" min="0" step="0.01" :class="{ error: errors.customPrice }">
          <div class="error-message" v-if="errors.customPrice">请填写自定义价格</div>
        </div>

        <div class="form-group">
          <label class="form-label required">平台抽成方式</label>
          <div class="commission-options">
            <div class="commission-option" :class="{ selected: form.commissionType === 'percentage' }" @click="form.commissionType = 'percentage'">
              <input type="radio" name="commission-type" v-model="form.commissionType" value="percentage">
              <label>按支付金额的5%收取</label>
            </div>
            <div class="commission-option" :class="{ selected: form.commissionType === 'fixed' }" @click="form.commissionType = 'fixed'">
              <input type="radio" name="commission-type" v-model="form.commissionType" value="fixed">
              <label>固定收取0.2元</label>
            </div>
          </div>
          <div class="error-message" v-if="errors.commissionType">请选择平台抽成方式</div>
        </div>

        <div class="commission-details" v-if="form.customPrice > 0 && form.commissionType">
          <h4>费用明细</h4>
          <div class="price-breakdown">
            <span>用户支付价格:</span>
            <span id="user-price">{{ form.customPrice.toFixed(2) }} 元</span>
          </div>
          <div class="price-breakdown">
            <span>平台抽成:</span>
            <span id="commission-amount">{{ commissionAmount.toFixed(2) }} 元</span>
          </div>
          <div class="price-breakdown total">
            <span>代拿员实收:</span>
            <span id="courier-income">{{ courierIncome.toFixed(2) }} 元</span>
          </div>
          <div class="commission-note">平台抽成将从用户支付的价格中扣除，代拿员实际收到的是扣除平台抽成后的金额</div>
        </div>

        <div class="form-group">
          <label class="form-label" for="remarks">备注信息</label>
          <input type="text" class="form-input" id="remarks" v-model="form.remarks" placeholder="可选：特殊要求、联系方式等">
        </div>

        <button type="button" class="submit-btn" @click="submitOrder" :disabled="!isFormValid">提交订单</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'

export default {
  name: 'CreateOrder',
  data() {
    const today = new Date()
    const formattedDate = today.toISOString().split('T')[0]
    const hours = String(today.getHours()).padStart(2, '0')
    const minutes = String(today.getMinutes()).padStart(2, '0')
    
    return {
      minDate: formattedDate,
      form: {
        expressCompany: '',
        expressType: '',
        packageCount: 1,
        packageSize: '',
        estimatedWeight: '',
        pickupCode: '',
        pickupAddress: '',
        deliveryAddress: '',
        deliveryTimeType: '',
        deliveryDate: formattedDate,
        deliveryTime: `${hours}:${minutes}`,
        customPrice: 0,
        commissionType: '',
        remarks: ''
      },
      errors: {
        packageCount: false,
        packageSize: false,
        estimatedWeight: false,
        pickupCode: false,
        pickupAddress: false,
        deliveryAddress: false,
        deliveryTime: false,
        customPrice: false,
        commissionType: false
      }
    }
  },
  computed: {
    commissionAmount() {
      if (this.form.commissionType === 'percentage') {
        return this.form.customPrice * 0.05
      } else if (this.form.commissionType === 'fixed') {
        return 0.2
      }
      return 0
    },
    courierIncome() {
      return this.form.customPrice - this.commissionAmount
    },
    isFormValid() {
      return !this.errors.packageCount && 
             !this.errors.packageSize && 
             !this.errors.estimatedWeight && 
             !this.errors.pickupCode && 
             !this.errors.pickupAddress && 
             !this.errors.deliveryAddress && 
             !this.errors.deliveryTime && 
             !this.errors.customPrice && 
             !this.errors.commissionType &&
             this.form.packageCount > 0 &&
             this.form.packageSize &&
             this.form.estimatedWeight &&
             this.form.pickupCode &&
             this.form.pickupAddress &&
             this.form.deliveryAddress &&
             this.form.deliveryTimeType &&
             this.form.customPrice > 0 &&
             this.form.commissionType
    }
  },
  watch: {
    'form.packageCount'(value) {
      this.errors.packageCount = !value || value < 1
    },
    'form.packageSize'(value) {
      this.errors.packageSize = !value
    },
    'form.estimatedWeight'(value) {
      this.errors.estimatedWeight = !value
    },
    'form.pickupCode'(value) {
      this.errors.pickupCode = !value
    },
    'form.pickupAddress'(value) {
      this.errors.pickupAddress = !value
    },
    'form.deliveryAddress'(value) {
      this.errors.deliveryAddress = !value
    },
    'form.deliveryTimeType'(value) {
      this.errors.deliveryTime = !value
    },
    'form.customPrice'(value) {
      this.errors.customPrice = !value || value <= 0
    },
    'form.commissionType'(value) {
      this.errors.commissionType = !value
    }
  },
  methods: {
    selectDeliveryTime(type) {
      this.form.deliveryTimeType = type
      if (type !== 'custom') {
        // 自动计算送达时间
        const now = new Date()
        const deliveryTime = new Date(now.getTime() + parseInt(type) * 60 * 60 * 1000)
        this.form.deliveryDate = deliveryTime.toISOString().split('T')[0]
        this.form.deliveryTime = deliveryTime.toTimeString().substring(0, 5)
      }
    },
    
    async submitOrder() {
      // 验证所有字段
      this.validateAllFields()
      
      if (!this.isFormValid) {
        ElMessage.error('请完善订单信息')
        return
      }

      try {
        // 获取当前用户信息
        const userId = localStorage.getItem('userId')
        const orderUserId = localStorage.getItem('orderUserId')
        
        if (!userId) {
          ElMessage.error('请先登录')
          this.$router.push('/login')
          return
        }

        // 准备订单数据
        const orderData = {
          userId: userId, // 后端会自动查找order_user_id
          order_user_id: orderUserId, // 如果有直接提供
          expressCompany: this.form.expressCompany,
          expressType: this.form.expressType,
          packageSize: this.form.packageSize,
          estimatedWeight: this.form.estimatedWeight,
          packageCount: this.form.packageCount,
          pickupCode: this.form.pickupCode,
          pickupAddress: this.form.pickupAddress,
          deliveryAddress: this.form.deliveryAddress,
          deliveryTimeType: this.form.deliveryTimeType,
          deliveryDate: this.form.deliveryDate,
          deliveryTime: this.form.deliveryTime,
          customPrice: this.form.customPrice,
          remarks: this.form.remarks || ''
        }

        // 调用后端API创建订单
        const response = await fetch('/api/orders', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(orderData)
        })

        const result = await response.json()

        if (result.success) {
          const deliveryTimeText = this.form.deliveryTimeType === 'custom' 
            ? `${this.form.deliveryDate} ${this.form.deliveryTime}`
            : `${this.form.deliveryTimeType}小时内送达`
          
          ElMessage.success(`订单创建成功！订单号：${result.data.orderId}`)
          
          // 重置表单
          this.resetForm()
          
          // 跳转到订单详情或订单列表
          if (result.data.orderId) {
            this.$router.push(`/order/detail/${result.data.orderId}`)
          } else {
            this.$router.push('/order/my')
          }
        } else {
          ElMessage.error(result.message || '订单创建失败')
        }
      } catch (error) {
        console.error('创建订单错误:', error)
        ElMessage.error('网络错误，请稍后再试')
      }
    },
    
    validateAllFields() {
      this.errors.packageCount = !this.form.packageCount || this.form.packageCount < 1
      this.errors.packageSize = !this.form.packageSize
      this.errors.estimatedWeight = !this.form.estimatedWeight
      this.errors.pickupCode = !this.form.pickupCode
      this.errors.pickupAddress = !this.form.pickupAddress
      this.errors.deliveryAddress = !this.form.deliveryAddress
      this.errors.deliveryTime = !this.form.deliveryTimeType
      this.errors.customPrice = !this.form.customPrice || this.form.customPrice <= 0
      this.errors.commissionType = !this.form.commissionType
    },
    
    resetForm() {
      this.form = {
        expressCompany: '',
        expressType: '',
        packageCount: 1,
        packageSize: '',
        estimatedWeight: '',
        pickupCode: '',
        pickupAddress: '',
        deliveryAddress: '',
        deliveryTimeType: '',
        deliveryDate: this.minDate,
        deliveryTime: new Date().toTimeString().substring(0, 5),
        customPrice: 0,
        commissionType: '',
        remarks: ''
      }
    }
  }
}
</script>

<style scoped>
/* 复制您创建订单页面的CSS样式 */
.create-order-page {
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  background: linear-gradient(135deg, #4a90e2, #5fa8ff);
  color: white;
  padding: 15px;
  position: relative;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.back-btn {
  font-size: 18px;
  cursor: pointer;
}

.header-title {
  font-size: 18px;
  font-weight: 500;
}

.placeholder {
  width: 24px;
}

.main-content {
  padding: 20px;
}

.form-container {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #555;
}

.required::after {
  content: " *";
  color: #e74c3c;
}

.form-select, .form-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  background-color: white;
  appearance: none;
  transition: border-color 0.3s;
}

.form-select:focus, .form-input:focus {
  border-color: #4a90e2;
  outline: none;
}

.form-select.error, .form-input.error {
  border-color: #e74c3c;
}

.select-wrapper {
  position: relative;
}

.select-wrapper::after {
  content: "▼";
  font-size: 12px;
  color: #666;
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  pointer-events: none;
}

.weight-example, .code-example {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.error-message {
  color: #e74c3c;
  font-size: 12px;
  margin-top: 5px;
}

.submit-btn {
  background: linear-gradient(135deg, #4a90e2, #67b26f);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 14px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  width: 100%;
  transition: opacity 0.3s;
  margin-top: 10px;
}

.submit-btn:hover:not(:disabled) {
  opacity: 0.9;
}

.submit-btn:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.commission-options {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 10px;
}

.commission-option {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.commission-option:hover {
  background-color: #f9f9f9;
}

.commission-option.selected {
  border-color: #4a90e2;
  background-color: #f0f7ff;
}

.commission-option input {
  margin-right: 10px;
}

.commission-details {
  margin-top: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #4a90e2;
}

.commission-details h4 {
  margin-bottom: 10px;
  color: #333;
}

.price-breakdown {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.price-breakdown.total {
  font-weight: bold;
  border-top: 1px solid #ddd;
  padding-top: 8px;
  margin-top: 8px;
}

.commission-note {
  font-size: 12px;
  color: #666;
  margin-top: 10px;
  font-style: italic;
}

.delivery-time-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.time-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 5px;
}

.time-option {
  flex: 1;
  min-width: 100px;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.time-option:hover {
  background-color: #f0f7ff;
}

.time-option.selected {
  background-color: #4a90e2;
  color: white;
  border-color: #4a90e2;
}

.datetime-inputs {
  display: flex;
  gap: 10px;
}

.date-input, .time-input {
  flex: 1;
}
</style>